package com.workManager.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.workManager.exception.BusinessException;
import com.workManager.mapper.TbCostEstimateMapper;
import com.workManager.mapper.TbProjectCostMapper;
import com.workManager.mapper.TbProjectMapper;
import com.workManager.mapper.TdOrganizationMapper;
import com.workManager.pojo.TbCostEstimate;
import com.workManager.pojo.TbProject;
import com.workManager.pojo.TbProjectCost;
import com.workManager.pojo.TdOrganization;
import com.workManager.util.ExcelReadUtil;
import com.workManager.vo.CostTrendsVo;
import com.workManager.vo.ProjectLaborCostVO;
import com.workManager.vo.ProjectVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by strangevy on 2017/5/18
 */
@Service
public class ProjectCostServiceImpl implements ProjectCostService {


    @Autowired
    private TbProjectCostMapper tbProjectCostMapper;

    @Autowired
    private TdOrganizationMapper tdOrganizationMapper;

    @Autowired
    private TbProjectMapper tbProjectMapper;

    @Autowired
    private TbCostEstimateMapper costEstimateMapper;

    @Transactional
    public void uploadExcel(String name, MultipartFile file) throws Exception {

        List<String[]> fileData = ExcelReadUtil.excelToList(name,file.getInputStream());

        String[] tableHead = fileData.get(0);
        String[] headTitle = {"年份", "月份", "部门", "项目编号", "总计"};
        for (int i = 0; i < headTitle.length; i++) {
            String headItem = tableHead[i];
            if (!headItem.equals(headTitle[i])) {
                throw new BusinessException("表格格式不正确！请检查表格格式重新上传。(行：1，列：" + (i + 1) + ")");
            }
        }

        //匹配金额
        String reg = "^-?[0-9]{1,8}(.[0-9]{1,2})?$";
        //匹配年月
        String regex = "^2[0-9]{3}-[0][1-9]|2[0-9]{3}-[1][0-2]$";

        List<TbProjectCost> newProjectCostList = new ArrayList<TbProjectCost>();
        Map<String, Object> conditionMap = new HashMap<String, Object>();
        String[] firstData = fileData.get(1);


        //设置月份
        String costYear = firstData[0];
        String costMonth = firstData[1];
        String costSalMonth = costMonth.trim().length() < 2 ? costYear.trim() + "-0" + costMonth.trim() : costYear.trim() + "-" + costMonth.trim();
        conditionMap.put("salMonth", costSalMonth);

        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 1; i < fileData.size(); i++) {
            String[] rowData = fileData.get(i);

            //检查是否空行
            if (ExcelReadUtil.isBlankRow(rowData)) {
                continue;
            }
            if (rowData[0] == null || "".equals(rowData[0])) {
                stringBuilder.append("年份不能为空！(行：" + (i+1) + "，列：1)")
                        .append(System.getProperty("line.separator"));
            }
            if (rowData[1] == null || "".equals(rowData[1])) {
                stringBuilder.append("月份不能为空！(行：" + (i+1) + "，列：2)")
                        .append(System.getProperty("line.separator"));
            }
            if (rowData[2] == null || "".equals(rowData[2])) {
                stringBuilder.append("部门不能为空！(行：" + (i+1) + "，列：3)")
                        .append(System.getProperty("line.separator"));
            }
            if (rowData[3] == null || "".equals(rowData[3])) {
                stringBuilder.append("项目编号不能为空！(行：" + (i+1) + "，列：4)")
                        .append(System.getProperty("line.separator"));
            }
            if (rowData[4] == null || "".equals(rowData[4])) {
                stringBuilder.append("总计不能为空！(行：" + (i+1) + "，列：5)")
                        .append(System.getProperty("line.separator"));
            }

            String year = rowData[0];
            String month = rowData[1];
            String orgName = rowData[2];
            String projectCode = rowData[3];
            String totalAmount = rowData[4];

            String salMonth = month.trim().length() < 2 ? year.trim() + "-0" + month.trim() : year.trim() + "-" + month.trim();
            if(!salMonth.matches(regex)){
                stringBuilder.append("请检查年月是否正确，年份请以2开头(行：" + (i+1) + "，列：1，2)")
                        .append(System.getProperty("line.separator"));
            }


            if (!totalAmount.matches(reg)) {
                stringBuilder.append("金额请精确到小数点后2位，整数位不大于8位(行：" + (i+1) + "，列：5)")
                        .append(System.getProperty("line.separator"));
            }


            TbProjectCost projectCost = new TbProjectCost();
            TdOrganization org = tdOrganizationMapper.queryByName(orgName);
            Map param = new HashMap();
            param.put("eqProjectCode",projectCode);
            List<ProjectVo> voList = tbProjectMapper.query(param);

            if (org == null) {
                stringBuilder.append("部门：" + orgName + " 不存在！(行：" + (i+1) + "，列：3)")
                        .append(System.getProperty("line.separator"));
            }
            if (voList == null || voList.size() == 0) {
                stringBuilder.append("项目编号：" + projectCode + " 不存在！(行：" + (i+1) + "，列：4)")
                        .append(System.getProperty("line.separator"));
            }else if(voList.get(0).getProjectStatusName()!=null&&voList.get(0).getProjectStatusName().equals("已完结")){
                stringBuilder.append("项目编号：" + projectCode + " 已完结！(行：" + (i+1) + "，列：4)")
                        .append(System.getProperty("line.separator"));
            }else if(voList.get(0).getProjectStatusName()!=null&&voList.get(0).getProjectStatusName().equals("已终结")){
                stringBuilder.append("项目编号：" + projectCode + " 已终结！(行：" + (i+1) + "，列：4)")
                        .append(System.getProperty("line.separator"));
            }

            if(stringBuilder.length() > 0){
                throw  new BusinessException(stringBuilder.toString());
            }

            ProjectVo tbProject = voList.get(0);
            projectCost.setSalMonth(salMonth);
            projectCost.setOrganizationId(org == null ? null : org.getOrganizationId());
            projectCost.setTotalAmount(new BigDecimal(totalAmount));
            projectCost.setProjectId(tbProject == null ?  null : tbProject.getProjectId());
            projectCost.setCreateDate(new Date());

            newProjectCostList.add(projectCost);

        }

        tbProjectCostMapper.deleteByConditions(conditionMap);


        Set<String> monthSet = new HashSet<>();
        for (TbProjectCost projectCost : newProjectCostList) {
            tbProjectCostMapper.insert(projectCost);
            //记录录入年月
            monthSet.add(projectCost.getSalMonth());
        }

        //报废人工预计表
        Map param = new HashMap();
        param.put("salMonths",monthSet);
        param.put("status","已发生");
        costEstimateMapper.invalid(param);
    }

    public PageInfo<ProjectLaborCostVO> countLaberCost(Map<String, Object> queryParam) {
        int pageno = !queryParam.containsKey("pagenum")||queryParam.get("pagenum")==null?1:Integer.parseInt(queryParam.get("pagenum").toString());
        int pagesize = !queryParam.containsKey("pagesize")||queryParam.get("pagesize")==null?10:Integer.parseInt(queryParam.get("pagesize").toString());
        PageHelper.startPage(pageno,pagesize);
        List<ProjectLaborCostVO> projectSalaryVoList = tbProjectCostMapper.countLaberCost(queryParam);
        PageInfo<ProjectLaborCostVO> pageInfo = new PageInfo<ProjectLaborCostVO>(projectSalaryVoList);
        return pageInfo;
    }

    public List<CostTrendsVo> countLaberCostByProjectIds(Map<String, Object> queryParam) {
        return tbProjectCostMapper.countLaberCostByProjectIds(queryParam);
    }


}
